<template>
    <div>
        <h2>登录</h2>
        <van-form @submit="onSubmit">
        <van-field
            v-model="username"
            name="username"
            label="用户名"
            placeholder="用户名"
            :rules="rules.username"
        />
        <van-field
            v-model="password"
            type="password"
            name="password"
            label="密码"
            placeholder="密码"
            :rules="rules.password"
        />
        <div style="margin: 16px;">
            <van-button round block type="info" native-type="submit">提交</van-button>
        </div>
        </van-form>
        还没有账号，请 <router-link to="/my/register">注册</router-link>
    </div>
</template>

<script>
import Vue from 'vue';
import { Form } from 'vant';
import { Field } from 'vant';
import {login} from '@/request'
import { Toast } from 'vant';
import {setCookie} from '@/utils/cookie'

Vue.use(Toast);
Vue.use(Form);
Vue.use(Field);
export default {
    data () {
        return {
        rules: {
            username: [
                {
                    required: true,
                    message: '请填写用户名' ,
                    trigger: 'onChange'
                }
            ],
            password: [
                {
                    required: true,
                    message: '请填写密码' ,
                    trigger: 'onChange'
                }
            ]
        },
        username: '',
        password: '',
    }
},
methods: {
    onSubmit(values) {
        var _this = this
      //console.log('submit', values);
      login(values).then(data => {
          var {code, msg} = data
          if (code === 1) {
              //成功
              //console.log('成功')
              Toast.success({
                  message: msg,
                  onClose() {
                      //存储cookie
                      setCookie('username',values.username,7200)
                      setCookie('nickname',data.data.nickname,7200)
                      //跳转
                      //_this.$router.push('/my')   

                      //购物车强行登录后再跳转回去,修改登录成功后的逻辑
                      var url = localStorage.getItem('url')
                      //跳转
                      if (url) {
                          //删除这个本地存储
                          localStorage.removeItem('url')
                          _this.$router.push(url)
                      } else {
                          _this.$router.push('/my')
                      }
                  }
              })
          } else {
              //失败
              //console.log('失败')
              Toast.fail(msg)
          }
      })
    },
}
}
</script>

<style scoped>
h2{
    text-align: center;
}
</style>